package com.lgl.scs.wx.service;

import com.lgl.scsapi.base.dao.DaoSupport;
import com.lgl.scsapi.system.model.AppUser;
import com.lgl.scsapi.system.model.PageData;
import com.lgl.scsapi.system.model.ServiceOrder;
import com.lgl.scsapi.system.model.UserRate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 微信小程序端订单处理service
 */
@Slf4j
@Service("wxUserRateService")
public class WxUserRateService {
	@Resource(name="wxServiceOrderService")
	private WxServiceOrderService wxServiceOrderService;
	@Resource(name = "daoSupport")
	private DaoSupport dao;

	/**
	 * 保存用户评论
	 * @param pd 保存的PageData参数
	 * @param user  当前登录用户
	 * @return PageData对象，包含code、isCommented两个key,code：成功或失败标识（0：成功，其它值表示失败），
	 * 			isCommented更新成功后的订单评价的状态值
	 * @throws Exception 抛出异常，回滚事务
	 */
	@Transactional(value = "scsTxManager",propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
	public PageData saveUserRate(PageData pd, AppUser user)throws Exception{
		String levelNum = pd.getString("levelNum"),userImpression = pd.getString("userImpression"),
				billId = pd.getString("billId"),rateText = pd.getString("rateText");
		if (!StringUtils.hasText(levelNum) || !StringUtils.hasText(userImpression) ||
			!StringUtils.hasText(billId) ||	!StringUtils.hasText(rateText)) {
			log.error("用户评价参数不全：userRatePd:" + pd);
			pd.clear();
			pd.put("code","1");
			return pd;
		}
		pd.put("statusArray",new Integer[]{2,3,7});
		ServiceOrder rateOrder = wxServiceOrderService.getServiceOrder(pd);
        if (rateOrder == null) {
			pd.clear();
			pd.put("code","2");
            return pd;
        }
        String personRated = rateOrder.getSoUserId(),userId = user.getUserId();
		//当前用户是发布人，对服务提供者进行评价
		if (personRated.equals(userId)) {
			personRated = rateOrder.getSoGetUser();
		}
		UserRate userRate = new UserRate();
		userRate.setRater(userId).setRateBillNo(rateOrder.getSoBillNumber()).setPersonRated(personRated)
				.setGrade(levelNum).setImpress(userImpression).setRateContent(rateText);
		int rows = saveUserRate(userRate);
		if (rows < 1) {
			pd.clear();
			pd.put("code","5");
			return pd;
		}
		//0：未评论；1:发布人、抢单人均已评论；2:发布人已评，抢单人未评；3：抢单人已评，发布人未评
		personRated = rateOrder.getSoUserId();
		String isCommented = String.valueOf(rateOrder.getIsCommented()), robUserId = rateOrder.getSoGetUser();
		//如果是发布人评价，且发布人、抢单人均未评价
		if (personRated.equals(userId) && "0".equals(isCommented)){
			isCommented = "2";
		}else if ((personRated.equals(userId) && "3".equals(isCommented)) || //如果是发布人评价，且抢单人已评
				(robUserId.equals(userId) && "2".equals(isCommented))){//如果是抢单人评价，且发布人已评价
			isCommented = "1";
		}else if (robUserId.equals(userId) && "0".equals(isCommented)){//如果是抢单人评价，且发布人、抢单人均未评价
			isCommented = "3";
		}
		pd.put("isCommented",isCommented);
		pd.put("billNumber",rateOrder.getSoBillNumber());
		rows = wxServiceOrderService.editServiceOrder(pd);
		if (rows < 1) {
			throw new Exception("保存用户评论失败");
		}
		pd.clear();
		pd.put("code",rows > 0 ? "0" : "5");
		pd.put("isCommented",isCommented);
		return pd;
	}

	/**
	 * 保存用户评价信息
	 * @param userRate 用户评价对像
	 * @return 保存成功的行数
	 */
	public int saveUserRate(UserRate userRate){
		return dao.save("WxUserRateMapper.saveUserRate", userRate);
	}
}